"""
Author        yongfa
Date          2022-07-18 09:22:01
LastEditTime  2022-07-18 09:43:03
LastEditors   yongfa
Description   数据模型
"""


from app.extensions.sqlalchemy import db, EntityModel as Base
from app.extensions.utils.enums import OperTypeEnum


class SystemLog(Base):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), comment='用户id')
    module = db.Column(db.String(50), comment='系统模块')
    auth = db.Column(db.String(100), comment='访问哪个权限')
    _type = db.Column('type', db.Integer, default=OperTypeEnum.OTHER.value, comment='操作类型')
    remote_addr = db.Column(db.String(100), comment='请求IP地址')
    path = db.Column(db.String(511), comment='请求路径')
    endpoint = db.Column(db.String(100), comment='端点')
    request_method = db.Column(db.String(20), comment='请求方法(GET、PUT...)')
    request_param = db.Column(db.JSON, comment='请求参数: path、query、body')
    message = db.Column(db.String(511), comment='日志信息')
    status_code = db.Column(db.Integer, comment='请求的http返回码')
    response_time = db.Column(db.Float, comment='请求的响应时间: 秒')

    # __mapper_args__ = {
    #     "order_by": Base.create_time.desc()
    # }

    @property
    def type(self):
        type_dict = {
            'OTHER': '其他',
            'CREATE': '新增',
            'UPDATE': '修改',
            'DELETE': '删除',
            'GRANT': '授权',
            'EXPORT': '导出',
            'IMPORT': '导入',
            'FORCE': '强退',
            'GEN_CODE': '生成代码',
            'CLEAN': '清空数据'
        }
        return type_dict[OperTypeEnum(self._type).name]

    @type.setter
    def type(self, raw):
        self._type = raw
